#!/bin/bash
# by yingnn on Feb-25-2014
set -e

function info() {
echo Usage: `basename $0` '[-o chr.fa] in.fa [chr]1'
exit 65
}

while getopts  ":o:" opts
do
	case  $opts  in
	o) out_name=$OPTARG;;
	\?) info
		exit 1;;
	esac
done
shift $(($OPTIND - 1))

if test $# -lt 2; then info; fi

# let num_plus=$2+1

# num0=`cat $1 |grep -m 1 -n -P "^>([C|c]hr)?$2\b" |cut -d : -f 1`
# num1=`cat $1 |grep -m1 -n -P "^>([C|c]hr)?${num_plus}\b" |cut -d : -f 1`
# let num1=$num1-1

# echo chr$2 starts at: $num0 1>&2
# echo chr$2 ends at: $num1 1>&2

# if test -z "$out_name"; then
# filename=chr$2.fa
# sed -n "$num0, ${num1}p" $1 > $filename
# else
# sed -n "$num0, ${num1}p" $1 > $out_name
# fi

fa=$1
chrs_info=`dirname $fa`/chrs.info.txt



if test ! -e $chrs_info;then
cat $fa |grep -n '>' |awk '{print $1}' > $chrs_info
fi

info=`cat $chrs_info |grep -A1 -P ">$2$"`

if
echo $info |grep ' '
then
	num0=`echo $info |cut -d' ' -f1|cut -d':' -f1`
	num1=`echo $info |cut -d' ' -f2|cut -d':' -f1`
	let num1=$num1-1
	echo $2 starts at: $num0
	echo $2 ends at: $num1
	
	if test -z "$out_name"; then
	filename=$2.fa
	sed -n ''"$num0"','"$num1"'p' $1 > $filename
	else
	sed -n ''"$num0"','"$num1"'p' $1 > $out_name
	fi


else
	num0=`echo $info |cut -d':' -f1`
	echo $2 starts at: $num0
	echo $2 ends at: '$'
	if test -z "$out_name"; then
	
	filename=$2.fa
	sed -n ''"$num0"',$p' $1 > $filename
	else
	sed -n ''"$num0"',$p' $1 > $out_name
	fi
	
fi

exit 0
